<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="form.title" />
          </el-form-item>
          <el-row>
            <el-col :span="6">
              <el-form-item label="类型" prop="articleType">
                <el-select v-model="form.articleType" clearable placeholder="类型" @change="typeSelect">
                  <el-option
                    v-for="item in dict.article_types"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-show="isClassType">
              <el-form-item label="类别">
                <el-select v-model="form.classType" filterable placeholder="请选择">
                  <el-option
                    v-for="item in queryTypeOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="6">
              <el-form-item label="作者">
                <el-input v-model="form.author"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否跳转" prop="isUrl">
                <el-radio-group v-model="form.isUrl" @change="isUrlSelect">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            
          </el-row> 
          <el-row>
            <el-col :span="10" v-show="isShowUrl">
              <el-form-item label="跳转链接">
                <el-input v-model="form.url"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="排序" prop="sort">
                <el-input v-model="form.sort" type="number"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio label="1">正常</el-radio>
                  <el-radio label="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="图片URL" v-show="isImageUrl">
              <MaterialList
                      v-model="form.imageUrlArr"
                      style="width: 915px;"
                      type="image"
                      :num="1"
                      :width="150"
                      :height="150"
              />
          </el-form-item>
          <el-form-item label="正文" v-show="!isShowUrl">
            <ueditor-wrap v-model="form.content" :config="myConfig"  @beforeInit="addCustomDialog"  style="line-height: initial;width: 90%;"></ueditor-wrap>
          </el-form-item> 
          <el-form-item>
            <el-button :loading="loading" type="primary" @click="doSubmit">保存</el-button>
          </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { add, edit, get } from '@/api/syArticleBannerManage'
import picUpload from '@/components/pic-upload'
import editor from '../../components/Editor'
import yamedit from '@/components/YamlEdit'
import MaterialList from '@/components/material'
import UeditorWrap from 'vue-ueditor-wrap';
export default {
  components: { editor, picUpload, yamedit, MaterialList, UeditorWrap },
  dicts: ['article_types', 'is_enable', 'is_enable', 'agree_ments','common_problems'],
  data() {
    return {
      queryTypeOptions: [],
      isShowUrl:false,
      isClassType:false,
      isImageUrl:true,
      loading: false, dialog: false,
      form: {
        id: '',
        title: '',
        imageUrl: '',
        content: '',
        author: 'yundangpu',
        imageUrlArr:[],
        articleType: '',
        classType: '',
        isUrl: '0',
        url: '',
        visit: '',
        sort: '',
        status: '1',
        createTime: '',
        updateTime: ''
      },
      rules: {
        id: [
          { required: true, message: '文章管理ID不能为空', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '文章标题不能为空', trigger: 'blur' }
        ],
        articleType: [
          { required: true, message: '文章类型', trigger: 'blur' }
        ],
        visit: [
          { required: true, message: '浏览次数不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ],
        isUrl: [
          { required: true, message: '是否跳转不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '正文否跳转不能为空', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '添加时间不能为空', trigger: 'blur' }
        ]
      },
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 500, // 初始容器高度
        initialFrameWidth: '100%', // 初始容器宽度
        UEDITOR_HOME_URL: '/UEditor/',
        serverUrl: ''
      }
    }
  },
  watch: {
    "imageUrlArr":function(val) {
      if (val) {
        this.form.imageUrl = val.join(",");
      }
    },
  },
  created() {
    this.form.id = this.$route.params.id
    this.$nextTick(() => {
      if(this.form.id){
        get(this.form.id).then(data => {     
          this.form = data;
          this.form.isUrl = data.isUrl.toString();
          this.form.status = data.status.toString();
          this.typeSelect();
          this.isUrlSelect();
          if (data.imageUrl) {
            this.form.imageUrlArr = data.imageUrl.split(",");
          }else{
            this.form.imageUrlArr=[]
          }
        })
      }

    })
  },
  methods: {
    typeSelect(){
      let that = this.form;
      if(that.articleType == '1'){//1：app协议
        this.isImageUrl = false;
        this.isClassType = true;
        this.queryTypeOptions = this.dict.agree_ments;
      }else if(that.articleType == '3'){//3：常见问题
        this.isImageUrl = true;
        this.isClassType = true;
        this.queryTypeOptions = this.dict.common_problems;
      }else{
        this.isClassType = false;
        this.isImageUrl = true;
      }
    },
    isUrlSelect(){
      let that = this.form;
      if(that.isUrl == '1'){//是否跳转（0：否1：是）
        this.isShowUrl = true;
      }else{
        this.isShowUrl = false;
      }
    },
    addCustomDialog () {
      window.UE.registerUI('yshop', function (editor, uiName) {
        let dialog = new window.UE.ui.Dialog({
          iframeUrl: '/yshop/materia/index',
          editor: editor,
          name: uiName,
          title: '上传图片',
          cssRules: 'width:1200px;height:500px;padding:20px;'
        });
        this.dialog = dialog;

        var btn = new window.UE.ui.Button({
          name: 'dialog-button',
          title: '上传图片',
          cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
          onclick: function () {
            dialog.render();
            dialog.open();
          }
        });

        return btn;
      }, 37);
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.loading = true
      if(this.form.imageUrlArr.length > 0){
        this.form.imageUrl = this.form.imageUrlArr.join(',')
      }else{
        this.form.imageUrl = ''
      }

      if (!this.form.id) {
        this.doAdd()
      } else this.doEdit()
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        setTimeout(() => {
          this.$router.push({ path: '/shop/syArticle' });
        }, 500);
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        setTimeout(() => {
          this.$router.push({ path: '/shop/syArticle' });
        }, 500);
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.form = {
        id: '',
        title: '',
        imageUrl: '',
        content: '',
        author: '',
        imageUrlArr:[],
        articleType: '',
        classType: '',
        isUrl: '',
        url: '',
        visit: '',
        sort: '',
        status: '',
        createTime: '',
        updateTime: ''
      }
    }
  }
}
</script>

<style scoped>

</style>
